package editorsvg.editor.formas;

import editorsvg.utilidades.Formato;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;

/**
 * Nodo perteneciente a un trayecto.
 * @author Jorge Berjano
 */
public class NodoTrayecto implements Cloneable {

    private Point2D posicion;
    private Point2D posicionControl1;
    private Point2D posicionControl2;
    private TipoNodo tipo;
    private float rx;
    private float ry;
    private float xAxisRotation;
    boolean largeArcFlag;
    boolean sweepFlag;

    public enum TipoNodo {

        MOVER, RECTA, CURVA_CUBICA, CURVA_CUADRATICA, ARCO, CERRAR
    };

    public NodoTrayecto(TipoNodo tipo, Point2D posicion) {
        this.posicion = posicion;
        this.tipo = tipo;
    }

    public NodoTrayecto(TipoNodo tipo, Point2D posicion, Point2D posicionControl1, Point2D posicionControl2) {
        this.posicion = posicion;
        this.posicionControl1 = posicionControl1;
        this.posicionControl2 = posicionControl2;
        this.tipo = tipo;
    }

    public NodoTrayecto(TipoNodo tipo, float rx, float ry, float xAxisRotation, boolean largeArcFlag, boolean sweepFlag, Point2D posicion) {
        this.tipo = tipo;
        this.posicion = posicion;
        this.rx = rx;
        this.ry = ry;
        this.xAxisRotation = xAxisRotation;
        this.largeArcFlag = largeArcFlag;
        this.sweepFlag = sweepFlag;
        this.posicion = posicion;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        switch (tipo) {
            case MOVER:
                return "M" + Formato.formatear(posicion);
            case RECTA:
                return "L" + Formato.formatear(posicion);
            case CURVA_CUBICA:
                return "C" + Formato.formatear(posicionControl1) + " " +
                        Formato.formatear(posicionControl2) + " " + Formato.formatear(posicion);
            case CURVA_CUADRATICA:
                return "Q" + Formato.formatear(posicionControl1) + " " +
                        Formato.formatear(posicion);
            case ARCO:
                return "A" + Formato.precision(rx) + "," + Formato.precision(ry) +
                        " " + Formato.precision(xAxisRotation) + " " +
                        (largeArcFlag ? 1 : 0) + "," + (sweepFlag ? 1 : 0) + " " + Formato.formatear(posicion);
            case CERRAR:
                return "Z";
            default:
                return "";
        }
    }

    public Point2D getPosicion() {
        return posicion;
    }

    public void setPosicion(Point2D punto) {
        this.posicion = punto;
    }

    public Point2D getPosicionControl1() {
        return posicionControl1;
    }

    public void setPosicionControl1(Point2D posicionControl1) {
        this.posicionControl1 = posicionControl1;
    }

    public Point2D getPosicionControl2() {
        return posicionControl2;
    }

    public void setPosicionControl2(Point2D posicionControl2) {
        this.posicionControl2 = posicionControl2;
    }

    /**
     * Obtiene la posición simetrica a la posición de control 1.
     * @return
     */
    public Point2D getSimetricaPosicionControl1() {
        if (posicion == null || posicionControl1 == null) {
            return null;
        }

        double dx = posicionControl1.getX() - posicion.getX();
        double dy = posicionControl1.getY() - posicion.getY();

        return new Point2D.Double(posicion.getX() - dx, posicion.getY() - dy);
    }

    public Point2D getSimetricaPosicionControl2() {
        if (posicion == null || posicionControl2 == null) {
            return null;
        }

        double dx = posicionControl2.getX() - posicion.getX();
        double dy = posicionControl2.getY() - posicion.getY();

        return new Point2D.Double(posicion.getX() - dx, posicion.getY() - dy);
    }

    public TipoNodo getTipo() {
        return tipo;
    }

    public void setTipo(TipoNodo tipo) {
        this.tipo = tipo;
    }

    public void agregarAlPath(Path2D path) {
        if (posicion == null && tipo != TipoNodo.CERRAR) {
            return;
        }
        switch (tipo) {
            case MOVER:
                path.moveTo(posicion.getX(), posicion.getY());
                break;
            case RECTA:
                path.lineTo(posicion.getX(), posicion.getY());
                break;
            case CURVA_CUBICA:
                if (posicionControl1 == null) {
                    posicionControl1 = posicion;
                }
                if (posicionControl2 == null) {
                    posicionControl2 = posicion;
                }
                path.curveTo(
                        posicionControl1.getX(), posicionControl1.getY(),
                        posicionControl2.getX(), posicionControl2.getY(),
                        posicion.getX(), posicion.getY());
                break;
            case CURVA_CUADRATICA:
                if (posicionControl1 == null) {
                    posicionControl1 = posicion;
                }
                path.quadTo(
                        posicionControl1.getX(), posicionControl1.getY(),
                        posicion.getX(), posicion.getY());
                break;
            case ARCO:
                //path.append(new Arc2D.Double(x, y, alto, ancho, anguloInicial, extensionAngular, Arc2D.OPEN), true);
                appendArcTo(path, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, (float) posicion.getX(), (float) posicion.getY());
                break;
            case CERRAR:
                //path.moveTo(posicion.getX(), posicion.getY());                
                path.closePath();
                break;
        }
    }

    /**
     * Adds an elliptical arc, defined by two radii, an angle from the
     * x-axis, a flag to choose the large arc or not, a flag to
     * indicate if we increase or decrease the angles and the final
     * point of the arc.
     *
     * @param rx the x radius of the ellipse
     * @param ry the y radius of the ellipse
     *
     * @param angle the angle from the x-axis of the current
     * coordinate system to the x-axis of the ellipse in degrees.
     *
     * @param largeArcFlag the large arc flag. If true the arc
     * spanning less than or equal to 180 degrees is chosen, otherwise
     * the arc spanning greater than 180 degrees is chosen
     *
     * @param sweepFlag the sweep flag. If true the line joining
     * center to arc sweeps through decreasing angles otherwise it
     * sweeps through increasing angles
     *
     * @param x the absolute x coordinate of the final point of the arc.
     * @param y the absolute y coordinate of the final point of the arc.
     */
    public void appendArcTo(Path2D path,
            float rx, float ry,
            float angle,
            boolean largeArcFlag,
            boolean sweepFlag,
            float x, float y) {

        // Ensure radii are valid
        if (rx == 0 || ry == 0) {
            path.lineTo(x, y);
            return;
        }

//        checkMoveTo();  // check if prev command was moveto

        // Get the current (x, y) coordinates of the path
        double x0 = path.getCurrentPoint().getX();
        double y0 = path.getCurrentPoint().getY();
        if (x0 == x && y0 == y) {
            // If the endpoints (x, y) and (x0, y0) are identical, then this
            // is equivalent to omitting the elliptical arc segment entirely.
            return;
        }

        Arc2D arc = computeArc(x0, y0, rx, ry, angle, largeArcFlag, sweepFlag, x, y);
        if (arc == null) {
            return;
        }
        AffineTransform t = AffineTransform.getRotateInstance(Math.toRadians(angle), arc.getCenterX(), arc.getCenterY());
        Shape s = t.createTransformedShape(arc);
        path.append(s, true);

//        makeRoom(7);
//        types[numSeg++] = ExtendedPathIterator.SEG_ARCTO;
//        values[numVals++] = rx;
//        values[numVals++] = ry;
//        values[numVals++] = angle;
//        values[numVals++] = largeArcFlag ? 1 : 0;
//        values[numVals++] = sweepFlag ? 1 : 0;
//        cx = values[numVals++] = x;
//        cy = values[numVals++] = y;
    }

    /**
     * This constructs an unrotated Arc2D from the SVG specification of an
     * Elliptical arc.  To get the final arc you need to apply a rotation
     * transform such as:
     *
     * AffineTransform.getRotateInstance
     *     (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2);
     */
    public static Arc2D computeArc(double x0, double y0,
            double rx, double ry,
            double angle,
            boolean largeArcFlag,
            boolean sweepFlag,
            double x, double y) {
        //
        // Elliptical arc implementation based on the SVG specification notes
        //

        // Compute the half distance between the current and the final point
        double dx2 = (x0 - x) / 2.0;
        double dy2 = (y0 - y) / 2.0;
        // Convert angle from degrees to radians
        angle = Math.toRadians(angle % 360.0);
        double cosAngle = Math.cos(angle);
        double sinAngle = Math.sin(angle);

        //
        // Step 1 : Compute (x1, y1)
        //
        double x1 = (cosAngle * dx2 + sinAngle * dy2);
        double y1 = (-sinAngle * dx2 + cosAngle * dy2);
        // Ensure radii are large enough
        rx = Math.abs(rx);
        ry = Math.abs(ry);
        double Prx = rx * rx;
        double Pry = ry * ry;
        double Px1 = x1 * x1;
        double Py1 = y1 * y1;
        // check that radii are large enough
        double radiiCheck = Px1 / Prx + Py1 / Pry;
        if (radiiCheck > 1) {
            rx = Math.sqrt(radiiCheck) * rx;
            ry = Math.sqrt(radiiCheck) * ry;
            Prx = rx * rx;
            Pry = ry * ry;
        }

        //
        // Step 2 : Compute (cx1, cy1)
        //
        double sign = (largeArcFlag == sweepFlag) ? -1 : 1;
        double sq = ((Prx * Pry) - (Prx * Py1) - (Pry * Px1)) / ((Prx * Py1) + (Pry * Px1));
        sq = (sq < 0) ? 0 : sq;
        double coef = (sign * Math.sqrt(sq));
        double cx1 = coef * ((rx * y1) / ry);
        double cy1 = coef * -((ry * x1) / rx);

        //
        // Step 3 : Compute (cx, cy) from (cx1, cy1)
        //
        double sx2 = (x0 + x) / 2.0;
        double sy2 = (y0 + y) / 2.0;
        double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1);
        double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1);

        //
        // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle)
        //
        double ux = (x1 - cx1) / rx;
        double uy = (y1 - cy1) / ry;
        double vx = (-x1 - cx1) / rx;
        double vy = (-y1 - cy1) / ry;
        double p, n;
        // Compute the angle start
        n = Math.sqrt((ux * ux) + (uy * uy));
        p = ux; // (1 * ux) + (0 * uy)

        sign = (uy < 0) ? -1.0 : 1.0;
        double angleStart = Math.toDegrees(sign * Math.acos(p / n));

        // Compute the angle extent
        n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
        p = ux * vx + uy * vy;
        sign = (ux * vy - uy * vx < 0) ? -1.0 : 1.0;
        double angleExtent = Math.toDegrees(sign * Math.acos(p / n));
        if (!sweepFlag && angleExtent > 0) {
            angleExtent -= 360f;
        } else if (sweepFlag && angleExtent < 0) {
            angleExtent += 360f;
        }
        angleExtent %= 360f;
        angleStart %= 360f;

        //
        // We can now build the resulting Arc2D in double precision
        //
        Arc2D.Double arc = new Arc2D.Double();
        arc.x = cx - rx;
        arc.y = cy - ry;
        arc.width = rx * 2.0;
        arc.height = ry * 2.0;
        arc.start = -angleStart;
        arc.extent = -angleExtent;

        return arc;
    }
}
